package com.hongdee.crm.carConfig.service.impl;

import com.hongdee.common.dao.IHibernateDao;
import com.hongdee.common.dao.IImpHibernateDao;
import com.hongdee.common.dao.IImpJdbcDao;
import com.hongdee.common.dao.IJdbcDao;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.carConfig.dao.ITCrmCarRefDetailDao;
import com.hongdee.crm.carConfig.entity.TCrmCarRefDetail;
import com.hongdee.crm.carConfig.service.ITCrmCarRefDetailService;
import com.hongdee.crm.task.service.ITCrmCarWorkorderTaskService;
import com.hongdee.crm.task.service.ITCrmTimeTaskService;
import com.hongdee.crm.task.vw.service.ITCrmVwTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by My on 2017/4/24.
 */
@Service
public class    TCrmCarRefDetailServiceImpl implements ITCrmCarRefDetailService {

    private String tabName = "t_crm_car_ref_detail";
    @Autowired
    private ITCrmCarRefDetailDao detailDao;

    @Autowired
    private IImpHibernateDao iImpHibernateDao;
    @Autowired
    private IImpJdbcDao iImpJdbcDao;

    @Autowired
    private IJdbcDao jdbcDao;
    @Autowired
    private IHibernateDao iHibernateDao;

    @Autowired
    private ITCrmVwTaskService vwTaskService;

    @Autowired
    private ITCrmTimeTaskService timeTaskService;

    @Autowired
    private ITCrmCarWorkorderTaskService itCrmCarWorkorderTaskService;
    /**
     * 导入信息颁布查询
     *
     * @param uid
     * @param start
     * @param limit
     * @return
     * @throws Exception
     */
    @Override
    public Map impPage(String uid, String start, String limit) throws Exception {
        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("select * from " + tabName + " where 1=1 ");
        String oId = TokenUtil.getCompanyId(uid);
        List params = new ArrayList();
        if (!StringUtils.isEmpty(oId)) {
            sqlBuffer.append(" and company_id = ? ");
            params.add(oId);
        }

        return iImpJdbcDao.queryForPageMap(start, limit, sqlBuffer.toString(), params.toArray());
    }

    /**
     * 单条导入
     *
     * @param id
     * @param uid
     * @throws Exception
     */
    @Override
    public void impConfirm(String id, String uid) throws Exception {
        String EXIST_DATA_SQL = "select * from " + tabName + " where vin = ? and u_name=? and company_id = ? limit 1";
        Map existData;
        String companyId = TokenUtil.getCompanyId(uid);
        List<Object> idList = new ArrayList();
        Object obj = this.iImpHibernateDao.findEntity(TCrmCarRefDetail.class, id);
        if (obj == null) {
            throw new Exception("无效的数据！");
        }
        TCrmCarRefDetail ex = (TCrmCarRefDetail) obj;
        existData = this.jdbcDao.queryForMapBySqlWithParams(EXIST_DATA_SQL, ex.getVin(), ex.getuName(), ex.getCompanyId());
        if (existData.size() == 0) {
            ex.setId(null);
            ex.setCreateTime(new Date().getTime());
            ex.setUpdateTime(new Date().getTime());
        } else {
            //已有数据
            ex.setId(existData.get("id").toString());
            ex.setUpdateTime(new Date().getTime());
        }

        idList.add(id);
        this.detailDao.saveOrUpdate(ex);
        this.iImpJdbcDao.batchDel(tabName, "id", idList);
        idList.clear();
        /* 更新车辆SVN对应人员ID */
        vwTaskService.updRefDetailUidQuartz();
//        vwTaskService.updDzTaskSaIdQuartz();
        /* 根据任务处理权限及车辆分配SVN更新任务SAID */
        timeTaskService.updCrmTaskSaId(companyId);
    }

    /**
     * @return
     * @throws Exception
     * @desc 删除全部待导入数据
     * @author 术洪超
     */
    @Override
    public void impDelAll(String uid) throws Exception {

        Map map = new HashMap();
        String companyId = TokenUtil.getCompanyId(uid);
        String hql = " delete from TCrmCarRefDetail where companyId =:companyId";
        map.put("companyId", companyId);
        this.iImpHibernateDao.executeHqlWithParams(hql, map);
    }

    @Override
    public void impDels(List<Map<Object, String>> data, String uid) throws Exception {
        List<Object> idList = new ArrayList();
        for (Map map : data) {
            idList.add(map.get("id"));
        }
        this.iImpJdbcDao.batchDel(tabName, "id", idList);
    }

    @Override
    public void multiImpConfirm(List<Map> data, String uid) throws Exception {
        TCrmCarRefDetail ex;
        Map existData;
        String companyId = TokenUtil.getCompanyId(uid);
        List<Object> idList = new ArrayList();
        for (Map map : data) {
            String EXIST_DATA_SQL = "select * from " + tabName + " where vin = ? and u_name=? and company_id = ? limit 1 ";
            String tempId = String.valueOf(map.get("id"));
            Map<String, Object> params = new HashMap<>();
            params.put("id", tempId);
            Object obj = iImpHibernateDao.findEntityByHqlWithParams("from TCrmCarRefDetail where id=:id", params);
            if (obj == null) {
                throw new Exception("无对应数据！");
            }
            ex = (TCrmCarRefDetail) obj;
            existData = this.jdbcDao.queryForMapBySqlWithParams(EXIST_DATA_SQL, ex.getVin(), ex.getuName(), ex.getCompanyId());
            //源数据主键
            idList.add(tempId);
            if (existData.size() == 0) {
                //新数据
                ex.setId(null);
                ex.setCreateTime(new Date().getTime());
                ex.setUpdateTime(new Date().getTime());
            } else {
                //已有数据
                ex.setId(existData.get("id").toString());
                ex.setUpdateTime(new Date().getTime());
            }
            this.detailDao.saveOrUpdate(ex);
        }
        this.iImpJdbcDao.batchDel(tabName, "id", idList);
        idList.clear();
         /* 更新车辆SVN对应人员ID */
        vwTaskService.updRefDetailUidQuartz();
//        vwTaskService.updDzTaskSaIdQuartz();
        /* 根据任务处理权限及车辆分配SVN更新任务SAID */
        timeTaskService.updCrmTaskSaId(companyId);
    }


    @Override
    public void impConfirmAll(String uid) throws Exception {
        //获取公司 ID
        String companyId = TokenUtil.getCompanyId(uid);
        //编写查询源数据 HQL
        String hql = "from TCrmCarRefDetail where companyId = :companyId";
        //设置参数
        Map<String, Object> params = new HashMap();
        params.put("companyId", companyId);
        //查询公司下的全部延保
        List<TCrmCarRefDetail> tCrmCarExsurance = iImpHibernateDao.findEntityListByHqlWithParams(hql, params);
        if (tCrmCarExsurance == null) {
            throw new Exception("无效的数据！");
        }
        //每50条保存一次
        List<Object> idList = new ArrayList<>();
        Map existData;
        String tempId;
        String EXIST_DATA_SQL = "select * from " + tabName + " where vin = ? and u_name=? and company_id = ? limit 1";
        for (TCrmCarRefDetail ex : tCrmCarExsurance) {
            existData = this.jdbcDao.queryForMapBySqlWithParams(EXIST_DATA_SQL, ex.getVin(), ex.getuName(), ex.getCompanyId());
            //源数据主键
            tempId = ex.getId();
            idList.add(tempId);
            if (existData.size() == 0) {
                ex.setId(null);
                ex.setCreateTime(new Date().getTime());
                ex.setUpdateTime(new Date().getTime());
            } else {
                //已有数据
                ex.setId(existData.get("id").toString());
                ex.setUpdateTime(new Date().getTime());
            }
            //保存或更新
            this.iHibernateDao.saveOrUpdateEntity(ex);
            if (idList.size() == 500) {
                this.iImpJdbcDao.batchDel(tabName, "id", idList);
                idList.clear();
            }
        }
        //处理剩余数据
        if (idList.size() > 0) {
            this.iImpJdbcDao.batchDel(tabName, "id", idList);
            idList.clear();
        }
        /* 更新车辆SVN对应人员ID */
        vwTaskService.updRefDetailUidQuartz();
//        vwTaskService.updDzTaskSaIdQuartz();
        /* 根据任务处理权限及车辆分配SVN更新任务SAID */
        timeTaskService.updCrmTaskSaId(companyId);
        //工单类型更新
        this.itCrmCarWorkorderTaskService.bulidWorkorderPropertyByCompanyQuqrtz(companyId);

    }

    /**
     * 车辆VIN分配查询
     *
     * @param start
     * @param limit
     * @param saId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> query(String companyId, String start, String limit, String saId, String distType, String allotType,
                                     String allotTypeV) throws Exception {
        List<String> params = new ArrayList<>();
        StringBuffer sqlStr = new StringBuffer();
        sqlStr.append("select car.vin,car.plate_num,detail.u_name, " +
                "DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT( FROM_UNIXTIME(car.guarantee_start_date / 1000), '%Y' ) AS carAge " +
                "from t_crm_car car " +
                "LEFT JOIN t_crm_car_ref_detail detail  " +
                "                ON car.vin=detail.vin and detail.company_id=car.company_id where car.company_id=? ");
        params.add(companyId);
        //distType 分配类型
        if ("0".equals(distType)) {
            sqlStr.append(" and detail.id is null ");
        } else if ("1".equals(distType)) {
            sqlStr.append(" and detail.id is not null ");
        }
        if (!StringUtils.isEmpty(saId)) {
            sqlStr.append(" and detail.uid=? ");
            params.add(saId);
        }
        // 车牌号
        if (!StringUtils.isEmpty(allotType)) {
            switch (allotType) {
                case "1":
                    sqlStr.append(" and car.plate_num like ? ");
                    params.add("%" + allotTypeV + "%");
                    break;
                case "2":
                    sqlStr.append(" and car.vin like ? ");
                    params.add("%" + allotTypeV + "%");
                    break;
                case "3":
                    if (!StringUtils.isEmpty(allotTypeV)) {
                        sqlStr.append(" AND  car.plate_num REGEXP ? ");
                        params.add("[" + allotTypeV.replaceAll(",", "") + "]$");
                    }
                    break;
                case "4":
                    if (!StringUtils.isEmpty(allotTypeV)) {
                        sqlStr.append(" AND car.plate_num REGEXP ? ");
                        params.add(".*[" + allotTypeV.replaceAll(",", "") + "][A-Za-z]*$");
                    }
                    break;
                default:
                    break;
            }

        }


        sqlStr.append("order by detail.u_name DESC ");
        return detailDao.page(sqlStr.toString(), params.toArray(), start, limit);
    }

    /**
     * 分配车辆尾号或尾数，根据尾号或尾数获得车辆信息并将该车辆分配给指定人员
     *
     * @param companyId
     * @param type
     * @param value
     * @param uid
     * @throws Exception
     */
    @Override
    public void distCarByPlateNum(String companyId, String type, String value, String uid) throws Exception {
        if (StringUtils.isEmpty(value)) {
            throw new Exception("未明确尾号或尾数！！");
        }
        Map userInfo = this.detailDao.info("T_BC_USER", "id", uid);
        StringBuffer sqlStr = new StringBuffer();
        sqlStr.append("insert into t_crm_car_ref_detail (id,uid,vin,company_id,u_name) ");
        String sql = "select car.id,'%s',car.vin,car.company_id,'%s' from t_crm_car car where NOT EXISTS(select 1 from t_crm_car_ref_detail where car.vin=vin) " +
                "and car.company_id=? ";
        sql = String.format(sql, uid, userInfo.get("uName"));
        sqlStr.append(sql);
        Map<String, Object> has = new HashMap<String, Object>();
        String tmps[] = null;
        //可能存在单个value字段1，2，3样式，需先分割开
        tmps = value.split(",");
        for (int j = 0; j < tmps.length; j++) {
            has.put(tmps[j], "1");
        }
        Object obj[] = has.keySet().toArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < obj.length; i++) {
            sb.append(obj[i].toString());
        }

        //0全部、1 尾号、2 尾数、3 VIN、
        // StringBuffer pdsql = new StringBuffer();
        //生成过滤语句
        if (type.equals("1")) {
            sqlStr.append(" AND car.plate_num REGEXP '[" + sb.toString().replaceAll(",", "") + "]$'  ");
        } else if (type.equals("2")) {
            sqlStr.append(" AND car.plate_num REGEXP '.*[" + sb.toString().replaceAll(",", "") + "][A-Za-z]*$' ");
        }
        this.detailDao.executeSQL(sqlStr.toString(), companyId);
        this.vwTaskService.updDzTaskSaIdQuartz();
    }

    /**
     * 批量分配车辆信息
     *
     * @param companyId
     * @param uid
     * @param data
     * @throws Exception
     */
    @Override
    public void distCarsByPlateNum(String companyId, String uid, List<Map> data) throws Exception {
        if (StringUtils.isEmpty(uid)) {
            throw new Exception("未选择人员");
        }
        StringBuffer vinStr = new StringBuffer();
        for (int i = 0; i < data.size(); i++) {
            Map<String, Object> map = data.get(i);
            vinStr.append("'" + map.get("vin").toString() + "'");
            if (i < (data.size() - 1)) {
                vinStr.append(",");
            }
        }
        Map userInfo = this.detailDao.info("T_BC_USER", "id", uid);
        //删除分配表内的vin号
        String delStr = "delete from t_crm_car_ref_detail where company_id=? and vin in (" + vinStr.toString() + ")";
        this.detailDao.executeSQL(delStr, companyId);
        //重新插入
        StringBuffer insStr = new StringBuffer().append("insert into t_crm_car_ref_detail (id,uid,vin,company_id,u_name) ");
        String sql = "select car.id,'%s',car.vin,car.company_id,'%s' from t_crm_car car where NOT EXISTS(select 1 from t_crm_car_ref_detail where car.vin=vin) " +
                "and car.company_id=? ";
        sql = String.format(sql, uid, userInfo.get("uName"));
        insStr.append(sql);
        insStr.append(" and car.vin in (");
        insStr.append(vinStr.toString());
        insStr.append(")");
        this.detailDao.executeSQL(insStr.toString(), companyId);
    }


}
